package cn.example.vip.mall.goods.seata;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class SeataDataSourceProxy {
	/**
	 * 获取数据源对象
	 */
	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	public DataSource druidDataSource() {
		return new DruidDataSource();
	}
	
//	/**
//	 * 导入MybatisPlus自定义映射
//	 * @param dataSource
//	 * @return
//	 * @throws Exception
//	 */
//	@Bean
//	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
//		MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
//		factoryBean.setDataSource(dataSource);
//		factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
//			.getResources("classpath*:mapper/*.xml"));
//		// 其他配置...
//		return factoryBean.getObject();
//	}
	
	/**
	 * 创建代理数据源
	 */
	@Bean
	public DataSourceProxy dataSourceProxy(DataSource druidDataSource){
		return new DataSourceProxy(druidDataSource);
	}

	/**
	 * 集成Mybatis-Plus
	 * 替换MybatisSqlSessionFactoryBean的DataSource
	 */
	@Bean
	public MybatisSqlSessionFactoryBean sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
		// 这里用 MybatisSqlSessionFactoryBean 代替了 SqlSessionFactoryBean，否则 MyBatisPlus 不会生效
		MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
		mybatisSqlSessionFactoryBean.setDataSource(dataSourceProxy);
		return mybatisSqlSessionFactoryBean;
	}
	
//	@Bean
//	public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
//		return new DataSourceTransactionManager(dataSource);
//	}
	
}
